const Proxy = require('../../proxy')
const reqlib = require('app-root-path').require
const quantityUtil = reqlib('/app/common/btb/quantityUtil')
const getMyBalanceInfo = require('./getMyBalanceInfo')

const BtbIndex = Proxy.BtbIndex
const ExecuteRecord = Proxy.ExecuteRecord

const exBuyXH = reqlib('/app/common/btb/exBuy')

const addExecuteRecord = async (config) => {
  await ExecuteRecord.newAndSave({
    code: config.code,
    market: 1,
    type: config.type,
    reason: 'manual',
    leverage: 1,
    quantity: config.quantity || 0,
    detail: {}
  })
}

module.exports = async function () {
  const query = {
    status: 1,
    xh_status: 1
  }
  // 找出币
  let btbRes = await BtbIndex.find(query, {
    sort: '-proportion'
  })
  // 总占比
  const btbIndexConfig = {
    proportionAll: 0,
    balance: {},
    btbList: []
  }
  // 查K线
  for (let i = 0; i < btbRes.length; i++) {
    const btbItem = btbRes[i]
    if (btbItem.proportion) {
      btbIndexConfig.proportionAll += btbItem.proportion
      btbIndexConfig.btbList.push({
        name: btbItem.name,
        code: btbItem.code,
        hourEma510: btbItem.hourEma510 || 0,
        hourEmaInfo: btbItem.hourEmaInfo ? btbItem.hourEmaInfo : {},
        dayEmaInfo: btbItem.dayEmaInfo ? btbItem.dayEmaInfo : {},
        strategy: btbItem.strategy,
        // 取合约的信息
        min_qty: btbItem.min_qty,
        max_qty: btbItem.max_qty,
        step_size: btbItem.step_size,
        min_notional: btbItem.min_notional,
        tick_size: btbItem.tick_size,
        proportion: btbItem.proportion
      })
    }
  }
  if (btbIndexConfig.btbList.length === 0) {
    return false
  }
  // 资产
  const myBalance = await getMyBalanceInfo()
  const allUsdt = myBalance['ALL'].usdt
  btbIndexConfig.btbList.forEach((v, index) => {
    const balanceInfo = myBalance[v.code]
    const position = ((allUsdt * v.proportion) / btbIndexConfig.proportionAll) - (balanceInfo.usdt || 0)
    btbIndexConfig.btbList[index] = {
      ...v,
      balance: balanceInfo.available || 0,
      price: balanceInfo.price || 0,
      usdt: balanceInfo.usdt || 0,
      shouldBuy: (position > 0 && balanceInfo.price) ? position : 0
    }
    btbIndexConfig.balance[v.code] = balanceInfo.available || 0
  })
  // 执行买入卖出
  for (let i = 0; i < btbIndexConfig.btbList.length; i++) {
    const btbItem = btbIndexConfig.btbList[i]
    if (btbItem.shouldBuy > 0) {
      // 平多，直接算持仓的数量
      const quantity = quantityUtil.formatMinBuy(btbItem.shouldBuy, btbItem, myBalance['USDT'].usdt)
      if (quantity) {
        const exRes = await exBuyXH({
          usdtKey: `${btbItem.code}USDT`,
          quantity: quantity,
          btbItem
        })
        if (exRes) {
          await addExecuteRecord({
            code: btbItem.code,
            type: 'buy',
            leverage: 1,
            quantity: exRes.executedQty,
            btbItem
          })
          await BtbIndex.update({ code: btbItem.code }, {
          })
        }
      }
    }
  }
  return {}
}
